package com.xfcy.blog.utils;

import com.google.code.kaptcha.text.impl.DefaultTextCreator;
import com.xfcy.blog.common.constant.Constant;

import java.util.Random;

/**
 * 验证码文本生成器
 * @author 晓风残月Lx
 * @date 2023/5/15 10:48
 */
public class CaptchaUtils extends DefaultTextCreator {

    @Override
    public String getText() {
        Integer result = 0;
        Random random = new Random();
        int x = random.nextInt(10);
        int y = random.nextInt(10);
        StringBuilder sb = new StringBuilder();
        // 取 0 1 2 3
        int randomType = (int) Math.round(Math.random() * 3);

        if (randomType == Constant.ZERO) {
            result = x + y;
            sb.append(x);
            sb.append("+");
            sb.append(y);
        } else if (randomType == Constant.ONE) {
            if (!(y == 0) && x % y == 0) {
                result = x / y;
                sb.append(x);
                sb.append("/");
                sb.append(y);
            } else {
                result = x + y;
                sb.append(x);
                sb.append("+");
                sb.append(y);
            }
        } else if (randomType == Constant.TWO) {
            if (x >= y) {
                result = x - y;
                sb.append(x);
                sb.append("-");
                sb.append(y);
            } else {
                result = y - x;
                sb.append(y);
                sb.append("-");
                sb.append(x);
            }
        } else {
            result = x + y;
            sb.append(x);
            sb.append("+");
            sb.append(y);
        }
        //返回运算表达式和结果，用@符号分割
        sb.append("=?@" + result);
        return sb.toString();
    }
}
